const canvas = document.getElementById('webgl')
const gl = getWebGLContext(canvas)

//此例 添加对片元着色器的第一次尝试 改变颜色


let VertexShaderSource =
    'attribute vec4 a_Position;\n' +
    'attribute float a_PointSize;\n' +
    'void main(){ \n' +
    '   gl_Position = a_Position;\n' +
    '   gl_PointSize = a_PointSize;\n' +
    '}\n'
let FragmentShaderSource =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' +
    'void main(){\n' +
    '    gl_FragColor = u_FragColor;\n' +
    '}\n'

function main() {
    initShaders(gl, VertexShaderSource, FragmentShaderSource)
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position')
    let a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize')
    let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor')
    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position')
        return
    }

    canvas.onmousedown = (e) => {
        click(e, gl, canvas, a_Position, u_FragColor)
    }
    gl.clearColor(0.5, 0.5, 0.5, 1)
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.vertexAttrib1f(a_PointSize, 15.0)
}


let g_points = []
let g_colors = []
function click(e, gl, canvas, a_Position, u_FragColor) {
    let x = e.clientX
    let y = e.clientY
    let rect = e.target.getBoundingClientRect()
    x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2)
    y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2)
    g_points.push([x, y])

    //处理位置对应的颜色关系
    if (x >= 0.0 && y >= 0.0) {
        g_colors.push([1.0, 0.0, 0.0, 1.0]) //红色
    } else if (x < 0.0 && y < 0.0) {
        g_colors.push([0.0, 1.0, 0.0, 1.0]) //绿色
    } else {
        g_colors.push([1.0, 1.0, 1.0, 1.0]) //白色
    }

    gl.clear(gl.COLOR_BUFFER_BIT)

    let len = g_points.length
    for (let i = 0; i < len; i++) {
        let xy = g_points[i]
        let rgba = g_colors[i]
        gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0)
        gl.uniform4f(u_FragColor, rgba[0], rgba[1], rgba[2], rgba[3])
        gl.drawArrays(gl.POINTS, 0, 1)
    }
}